package com.luban.springboot.controller;

import java.io.File;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {
	
	@Value("${img.imagesPath}")
	private String imgPath;

	@RequestMapping("/file")
	public String file() {
		return "file";
	}
	
	/**
	 * 上传文件
	 * @param modle
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/uploadFile",produces="application/json;charset=UTF-8")
    public String uploadFile(Model modle, @RequestParam("fileName") MultipartFile file) {
		String url = getUpUrl(file);
		modle.addAttribute("url",url);
		return "file";
	}
	
	public String getUpUrl(MultipartFile file) {
		if (file.isEmpty()) {
			return "文件不能空";
		}
		
		String fileName = file.getOriginalFilename();
		fileName = System.currentTimeMillis()+"_"+fileName;
		String path = imgPath+fileName;
		File dest = new File(path);
		
		if (dest.exists()) {
			return "文件已经存在";
		}
		
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		String url="";
		try {
			file.transferTo(dest);
			url="http://localhost:8080/luban/"+fileName;
		} catch (Exception e) {
			return "上传失败";
		}
		return url;
	}
}
